package cn.ant.mqHandle;

import cn.ant.config.RabbitMQConfig;
import cn.ant.entity.MessageSendDTO;
import com.alibaba.fastjson2.JSONObject;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 消费者类信息
 *
 * @author Anhui AntLaddie <a href="https://juejin.cn/user/4092805620185316">(掘金蚂蚁小哥)</a>
 * @version 1.0
 **/
@Slf4j
@Component
public class ConsumerA {

    /***
     * 消费者
     */
    @RabbitListener(queues = {RabbitMQConfig.CONFIRM_QUEUE}, ackMode = "MANUAL")
    public void consumerATest(@Payload String msgData, //这个是生产者发送的JSON消息
                              @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag, //处理消息的编号
                              @Header(AmqpHeaders.RECEIVED_ROUTING_KEY) String routingKey,
                              Message message,
                              Channel channel) throws IOException {
        // 把接收过来的JSON信息转换为对象
        try {
            MessageSendDTO messageSendDTO = JSONObject.parseObject(msgData, MessageSendDTO.class);
            //队列名称
            String consumerQueue = message.getMessageProperties().getConsumerQueue();
            log.info("消费者从队列：{} 获取消息：{}，并处理完成手动确认", consumerQueue, messageSendDTO);
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            log.info("消费失败：{}", msgData);
            channel.basicNack(deliveryTag, false, true);
        }
    }
}